/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javacommunity.controller.bean;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import com.javacommunity.model.dao.UserDAO;
import com.javacommunity.model.dao.impl.UserDAOImpl;
import com.javacommunity.model.entity.User;
import com.javacommunity.util.Constants;
import com.javacommunity.util.Support;
import java.util.ResourceBundle;
import javax.faces.bean.ManagedProperty;

/**
 *
 * @author Cong Pham Dinh
 */
@ManagedBean
@RequestScoped
public class Authentication {

    private final UserDAO USER_SERVICE = UserDAOImpl.getInstance();
    private User user = new User();
    
    @ManagedProperty("#{msg}")
    private ResourceBundle msg;

    public String getText(){
        return msg.getString("loginSuccess");
    }
    
    public String checkLogin() {
        String page = "";
        String userName = this.user.getUserName();
        String password = Support.encryptMD5(this.user.getPwd());
        if (USER_SERVICE.checkLogin(userName, password)) {
            User u = USER_SERVICE.getUserByUserName(userName);
            if (u.isActive()) {
                page = "/pages/index.jsf?faces-redirect=true";
                this.addMessages(msg.getString("loginSuccess"));
                HttpSession session = Support.getSession();
                session.setAttribute(Constants.CURRENT_USER, u);
                session.setMaxInactiveInterval(30 * 60);
            } else {
                page = "/module/success.jsf";
            }
        } else {
            this.addMessages(msg.getString("loginFailed"));
        }

        return page;
    }

    public String logout() {
        HttpSession session = Support.getSession();
        session.invalidate();
        return "index.jsf?faces-redirect=true";
    }

    public void addMessages(String message) {
        FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, message, "Message!");
        FacesContext.getCurrentInstance()
                .addMessage(null, fm);
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public ResourceBundle getMsg() {
        return msg;
    }

    public void setMsg(ResourceBundle msg) {
        this.msg = msg;
    }

}
